<script setup>
import { onMounted, ref } from 'vue'
import axios from 'axios'
import powerSet from './power-set.js'
// 商品数据
const goods = ref({})
let pathMap = {}
const getGoods = async () => {
  // 1135076  初始化就有无库存的规格
  // 1369155859933827074 更新之后有无库存项（蓝色-20cm-中国）
  const res = await axios.get('http://pcapi-xiaotuxian-front-devtest.itheima.net/goods?id=1369155859933827074')
  goods.value = res.data.result
  goods.value.specs.forEach(item => {
    item.values.forEach(spec => spec.selected = false)
  })
  pathMap = getPathMap(goods.value)
  initDisabledStatus(goods.value.specs, pathMap)
}
onMounted(() => getGoods())

const changeSku = (item, val) => {
  if (val.disabled) return
    if (val.selected) {
        val.selected = false
    } else {
        item.values.forEach(spec => spec.selected = false)
        val.selected = true
    }

    // 更新禁用状态
    updateDisabledStatus(goods.value.specs, pathMap)

    // 产出sku
    const selectedValArr = getSelectedValues(goods.value.specs)
    const index = selectedValArr.findIndex(item => item === undefined)
    if (index == -1) {
      const key = selectedValArr.join('-')
      const skuIds = pathMap[key] // 返回数组
      const skuObj = goods.value.skus.find(sku => sku.id == skuIds[0])
      console.log('sku', skuObj)
      return skuObj
    }
}

// 生成有效路径字典对象
const getPathMap = (goods) => {
    const pathMap = {}
    // 1. 根据sku字段生成有效的sku数组
    const effectiveSkus = goods.skus.filter(sku => sku.inventory > 0)
    effectiveSkus.forEach(sku => {
        // sku属性值
        const selectedValArr = sku.specs.map(val => val.valueName)
        // console.log('selectedValArr', selectedValArr) ['黑色', '10cm', '中国']
        // 使用算法获取子集
        const valueArrPowerSet = powerSet(selectedValArr)
        // console.log('valueArrPowerSet', valueArrPowerSet) 
        // 把得到的子集生成最终的路径字典对象
        valueArrPowerSet.forEach(arr => {
            const key = arr.join('-')
            if (pathMap[key]) {
                pathMap[key].push(sku.id)
            } else {
                pathMap[key] = [sku.id]
            }
        })
        // console.log('pathMap', pathMap)
    })
    return pathMap
}

// 初始化禁用状态
const initDisabledStatus = (specs, pathMap) => {
  specs.forEach(spec => {
    spec.values.forEach(val => {
      if (pathMap[val.name]) {
        val.disabled = false
      } else {
        val.disabled = true
      }
    })
  })
  // console.log('specs', specs)
}

// 获取选中项的匹配数组
const getSelectedValues = (specs) => {
  const arr = []
  specs.forEach(spec => {
    // 找到values中selected为true的项
    const selectedVal = spec.values.find(item => item.selected)
    arr.push(selectedVal ? selectedVal.name : undefined)
  })
  return arr
}

// 切换时更新禁用状态
const updateDisabledStatus = (specs, pathMap) => {
  specs.forEach((spec, index) => {
    const selectedValues = getSelectedValues(specs)
    spec.values.forEach(val => {
      selectedValues[index] = val.name
      const key = selectedValues.filter(value => value).join('-')
      if (pathMap[key]) {
        val.disabled = false
      } else {
        val.disabled = true
      }
    })
  })
}
</script>

<template>
  <div class="goods-sku">
    <dl v-for="item in goods.specs" :key="item.id">
      <dt>{{ item.name }}</dt>
      <dd>
        <template v-for="val in item.values" :key="val.name">
          <!-- 图片类型规格 -->
          <img v-if="val.picture" :src="val.picture" :title="val.name" @click="changeSku(item, val)" :class="{ selected: val.selected, disabled: val.disabled }" >
          <!-- 文字类型规格 -->
          <span v-else @click="changeSku(item, val)" :class="{ selected: val.selected, disabled: val.disabled }" >{{ val.name }}</span>
        </template>
      </dd>
    </dl>
  </div>
</template>

<style scoped lang="scss">
@mixin sku-state-mixin {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;

  &.selected {
    border-color: #27ba9b;
  }

  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}

.goods-sku {
  padding-left: 10px;
  padding-top: 20px;

  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;

    dt {
      width: 50px;
      color: #999;
    }

    dd {
      flex: 1;
      color: #666;

      >img {
        width: 50px;
        height: 50px;
        margin-bottom: 4px;
        @include sku-state-mixin;
      }

      >span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        margin-bottom: 4px;
        @include sku-state-mixin;
      }
    }
  }
}
</style>